package com.cloudpivot.receivales.ding.basic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkrobot_1_0.Client;
import com.aliyun.teaopenapi.models.Config;
import com.cloudpivot.receivales.ding.basic.service.DingBasicService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class DingBasicServiceImpl implements DingBasicService {

    @Autowired
    private RequestConfig config;

    @Autowired
    private CloseableHttpClient httpClient;

    //中台URL--- 从中台获取token
    @Value("${myprops.cpurl}")
    private String CPURL;

    @Override
    public String getToken(String tag) {
        String url = String.format("%s/api/systemInteg/getTokenByAppTag?appTag=%s", CPURL, tag);

        try {
            HttpGet httpGet = new HttpGet(url);
            // 装载配置信息
            httpGet.setConfig(config);
            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpGet);
            // 判断状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                String ret = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(ret);
                log.info("获取token:{}", jsonObject.toString());
                if (jsonObject.getInteger("code") == 1) {
                    return jsonObject.getString("msg");
                } else {
                    return null;
                }
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Client createClient() {
        try {
            Config config = new Config();
            config.protocol = "https";
            config.regionId = "central";
            return new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
